#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HeilongjiangPolicy(BaseTaxPolicySpider):
    name = 'heilongjiang_policy'
    
    province = '黑龙江省'
    city: str = ""  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['黑龙江省人民政府', "", "https://www.hlj.gov.cn/hlj/c108372/zfxxgk_search.shtml"],
            ['黑龙江省人民政府', "", "https://www.hlj.gov.cn/hlj/c108373/zfxxgk_search.shtml"],
            ['黑龙江省人民政府', "", "https://www.hlj.gov.cn/hlj/c108376/zfxxgk.shtml"],
            ['黑龙江省人民政府', "", "https://www.hlj.gov.cn/hlj/c108381/zfxxgk.shtml"],
            ['黑龙江省科学技术厅', "", "https://kjt.hlj.gov.cn/kjt/c113914/common_zfxxgk.shtml?tab=gkzc"],
            ['黑龙江省商务厅', "", "https://sswt.hlj.gov.cn/sswt/c103665/zfxxgk.shtml?tab=qtwj"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item})

    def parse_content(self, response, **kwargs):
        meta = response.meta
        channelId = response.xpath('//meta[@name="channelId" or @id="channelId"]/@content').get()
        if not channelId:
            channelId = response.xpath(""".""").re_first(r'channelId\s*=\s*"(.*?)"\;')
        params = {
            "sort": "",
            "_isAgg": "true",
            "_isJson": "true",
            "_pageSize": "20",
            "_template": "index",
            "_rangeTimeGte": "",
            "_rangeTimeLt": "",
            "_channelName": "",
            "page": "1"
        }
        "https://kjt.hlj.gov.cn/common/search/67aad941b15548328e7244a60615123e?_isAgg=true&_isJson=true&_pageSize=20&_template=index&_rangeTimeGte=&_channelName=&page=1"
        url = '/common/search/' + channelId + '?'
        meta['params'] = params
        meta['url'] = url
        yield response.follow(url + urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        datas = response.json()['data']

        for elem in datas['results']:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['publishedTimeStr'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total = datas['total']
            total_page = math.ceil(total / 20)
            print(response.url, "page:", total_page)
            for page_num in range(1, int(total_page) + 1):
                url = meta['url']
                params = meta['params']
                params['page'] = str(page_num)
                yield response.follow(url + urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl heilongjiang_policy".split())
